package com.ts.manager;

import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.Range;
import com.ts.host.APP;

public class OssDownloadMananger {
	
	private OSS mOss;
    // 运行sample前需要配置以下字段为有效的值
	  private static String endpoint = "http://oss-cn-shanghai.aliyuncs.com/";
 	  private static final String accessKeyId = "L6byQ1IaA8CnomF9";
	  private static final String accessKeySecret = "6Pm5CwuUH3BG2MNJndpUS8urk4lHNw";
	  
	  private static OssDownloadMananger mOssDownloadMananger;
		
		
		public static OssDownloadMananger getInstance(){
			if(mOssDownloadMananger == null){
				mOssDownloadMananger = new OssDownloadMananger();
			}
			return mOssDownloadMananger;
		}
		
	  
		public OSS getOSS() {
			if (mOss == null) {
				OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(
						accessKeyId, accessKeySecret);

				ClientConfiguration conf = new ClientConfiguration();
				conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
				conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
				conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
				conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
				OSSLog.enableLog();
				mOss = new OSSClient(APP.getInstance().getApplicationContext(),
						endpoint, credentialProvider, conf);
			}
			return mOss;
		}
		
		

	    public void getObjectSample(String testBucket,String testObject) {

	        // 构造下载文件请求
	        GetObjectRequest get = new GetObjectRequest(testBucket, testObject);

	        try {
	            // 同步执行下载请求，返回结果
	            GetObjectResult getResult = getOSS().getObject(get);

	            Log.d("Content-Length", "" + getResult.getContentLength());

	            // 获取文件输入流
	            InputStream inputStream = getResult.getObjectContent();

	            byte[] buffer = new byte[2048];
	            int len;

	            while ((len = inputStream.read(buffer)) != -1) {
	                // 处理下载的数据，比如图片展示或者写入文件等
	                Log.d("asyncGetObjectSample", "read length: " + len);
	            }
	            Log.d("asyncGetObjectSample", "download success.");

	            // 下载后可以查看文件元信息
	            ObjectMetadata metadata = getResult.getMetadata();
	            Log.d("ContentType", metadata.getContentType());


	        } catch (ClientException e) {
	            // 本地异常如网络异常等
	            e.printStackTrace();
	        } catch (ServiceException e) {
	            // 服务异常
	            Log.e("RequestId", e.getRequestId());
	            Log.e("ErrorCode", e.getErrorCode());
	            Log.e("HostId", e.getHostId());
	            Log.e("RawMessage", e.getRawMessage());
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }

	    public void asyncGetObjectSample(String testBucket,String testObject) {

	        GetObjectRequest get = new GetObjectRequest(testBucket, testObject);

	        OSSAsyncTask task = getOSS().asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
	            @Override
	            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
	                // 请求成功
	                InputStream inputStream = result.getObjectContent();

	                byte[] buffer = new byte[2048];
	                int len;

	                try {
	                    while ((len = inputStream.read(buffer)) != -1) {
	                        // 处理下载的数据
	                        Log.d("asyncGetObjectSample", "read length: " + len);
	                    }
	                    Log.d("asyncGetObjectSample", "download success.");
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }

	            @Override
	            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
	                // 请求异常
	                if (clientExcepion != null) {
	                    // 本地异常如网络异常等
	                    clientExcepion.printStackTrace();
	                }
	                if (serviceException != null) {
	                    // 服务异常
	                    Log.e("ErrorCode", serviceException.getErrorCode());
	                    Log.e("RequestId", serviceException.getRequestId());
	                    Log.e("HostId", serviceException.getHostId());
	                    Log.e("RawMessage", serviceException.getRawMessage());
	                }
	            }
	        });
	    }

	    /**
	     * 支持断点下载
	     * @param testBucket
	     * @param testObject
	     * @param begin
	     * @param end
	     */
	    public void asyncGetObjectRangeSample(String testBucket,String testObject,long begin, long end, OSSCompletedCallback<GetObjectRequest, GetObjectResult> callback) {

	        GetObjectRequest get = new GetObjectRequest(testBucket, testObject);
	        // 设置范围
	        get.setRange(new Range(begin, end));
	        OSSAsyncTask task = getOSS().asyncGetObject(get, callback);
	    }
		
}
